package com.mycjj.android.activity;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mycjj.android.ProjectDataManage;
import com.mycjj.android.R;
import com.mycjj.android.adapter.StoreAdapter;
import com.mycjj.android.adapter.TAdapter;
import com.mycjj.android.bean.BaseBean;
import com.mycjj.android.bean.CarInfoBaseBean;
import com.mycjj.android.bean.CarInfoBaseBean.CarInfo;
import com.mycjj.android.bean.DistanceAscComparator;
import com.mycjj.android.bean.DistanceDescComparator;
import com.mycjj.android.bean.StoreBaseBean;
import com.mycjj.android.bean.StoreBaseBean.Store;
import com.mycjj.android.bean.TreeElement;
import com.mycjj.android.http.ProjectHttpRequestImpl;
import com.mycjj.android.http.ProjectHttpRequestInterface;
import com.mycjj.android.util.Preferences;

public class BindStoreActivity extends BaseActivity implements
		android.view.View.OnClickListener {
	private String token;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bind_store);
		mActManager.pushActivity(REGISTER_KEY, this);
		initHeader();
		init();
		initData();
	}

	private ImageView mHeaderLeftImageview;
	private Button mHeaderRightButton;
	private TextView mHeaderTitleTextView;

	private void initHeader() {
		mHeaderLeftImageview = (ImageView) findViewById(R.id.header_left_button);
		mHeaderLeftImageview.setImageResource(R.drawable.back);
		mHeaderRightButton = (Button) findViewById(R.id.header_right_button);
		mHeaderRightButton.setVisibility(View.GONE);
		mHeaderTitleTextView = (TextView) findViewById(R.id.header_title_textview);
		mHeaderTitleTextView.setText("绑定服务点");
		mHeaderLeftImageview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				back();
			}
		});
	}

	private void back() {
		if (mChildView02.getVisibility() == View.VISIBLE) {
			mChildView02.setVisibility(View.GONE);
			mChildView01.setVisibility(View.VISIBLE);
		} else if (mChildView01.getVisibility() == View.VISIBLE) {
			mActManager.popActivity(REGISTER_KEY, BindStoreActivity.this);
		}
	}
	

	private ListView mListview;
	private TAdapter<Store> adapter;
	private View mChildView01, mChildView02;
	private Store currentStore;

	private ImageView header_pic;
	private TextView tv_name, tv_other_name;
	private TextView tv_address;
	private TextView tv_distance;
	private View item_02_view, item_01_view;
	private RadioButton rb01, rb02;
	private Button mBindButton;
	private View rl_item_01, rl_item_02, rl_item_03;
	private TextView tv_city;

	private int type_action;
	private void init() {
		token = Preferences.getSharedPreferences(this, "user_token", "");
		Intent intent = getIntent();
		if (intent != null) {
			bundle = intent.getExtras();
			type_action = intent.getIntExtra("type_action", 0);
		}
		if (TextUtils.isEmpty(token)) {
			Toast.makeText(this, "会话超时!", Toast.LENGTH_LONG).show();
			return;
		}
		mChildView01 = findViewById(R.id.child_view01);// 元宝
		mChildView02 = findViewById(R.id.child_view02);// listview
		rl_item_01 = findViewById(R.id.rl_item_01);
		rl_item_02 = findViewById(R.id.rl_item_02);
		rl_item_03 = findViewById(R.id.rl_item_03);
		tv_city = (TextView) findViewById(R.id.tv_temp3);
		if (!TextUtils.isEmpty(mApp.getNowCity())) {
			tv_city.setText(mApp.getNowCity());
		}
		rl_item_01.setOnClickListener(viewOnClickListener);
		rl_item_02.setOnClickListener(viewOnClickListener);
		mListview = (ListView) findViewById(R.id.listview);
		adapter = new StoreAdapter(this);
		mListview.setAdapter(adapter);

		header_pic = (ImageView) findViewById(R.id.header_pic);
		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_other_name = (TextView) findViewById(R.id.tv_other_name);
		tv_address = (TextView) findViewById(R.id.tv_address);
		tv_distance = (TextView) findViewById(R.id.tv_distance);
		rb01 = (RadioButton) findViewById(R.id.rb_01);
		rb02 = (RadioButton) findViewById(R.id.rb_02);
		rb02.setVisibility(View.INVISIBLE);
		item_01_view = findViewById(R.id.item_01);
		item_01_view.setVisibility(View.GONE);
		item_01_view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				rb01.setChecked(true);
				rb02.setChecked(false);
			}
		});
		item_02_view = findViewById(R.id.item_02);
		item_02_view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				rb01.setChecked(false);
				rb02.setChecked(true);
				mChildView01.setVisibility(View.GONE);
				mChildView02.setVisibility(View.VISIBLE);
			}
		});
		mListview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				if (storeList != null && storeList.size() > 0) {
					if (position >= storeList.size()) {
						Log.e("mark", "position:" + position
								+ ";storeList.size:" + storeList.size());
						return;
					}
					currentStore = storeList.get(position);
					Preferences.setEditor(mApp, "storeId", String.valueOf(currentStore.getStore_id()));
					Preferences.setEditor(mApp, "storeName",currentStore.getStore_name());
					Preferences.setEditor(mApp, "storeAddress",currentStore.getStore_address());
					Preferences.setEditor(mApp, "storeTel",currentStore.getStore_tel());
					changeView();
				}
			}
		});
		mBindButton = (Button) findViewById(R.id.btn_bind);
		mBindButton.setOnClickListener(this);
	}

	private void changeView() {
		rb01.setChecked(true);
		rb02.setChecked(false);
		imageLoader.displayImage(currentStore.getStore_logo(), header_pic);
		tv_name.setText(currentStore.getStore_name());
		tv_address.setText(currentStore.getStore_address());
		// TODO: set Distance
		tv_distance.setText("500m");
		tv_other_name.setText(currentStore.getStore_name());
		mChildView01.setVisibility(View.VISIBLE);
		mChildView02.setVisibility(View.GONE);
	}

	private boolean isDesc = false;
	private OnClickListener viewOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.rl_item_01:
				initData();
				break;
			case R.id.rl_item_02:
				if (isDesc) {// 当前降序
					isDesc = false;
					// 升序
					Collections.sort(storeList, new DistanceAscComparator());
				} else {// 当前升序
					isDesc = true;
					// 降序
					Collections.sort(storeList, new DistanceDescComparator());
				}
				adapter.setList(storeList);
				break;
			}
		}
	};

	private List<Store> storeList;
	private Bundle bundle;

	private void initData() {
		request = new ProjectHttpRequestImpl(this, true);
		RequestParams params = new RequestParams();
		// TODO:获取定位城市名称
		params.put("area_id", String.valueOf(mApp.getNowCityId()));
		params.put("limit", "100");
		params.put("offset", "0");
		params.put("client_id", ProjectHttpRequestInterface.client_id_key);
		params.put("token", token);
		TreeElement treeElement = dataManager.getElement();
		if (treeElement != null) {
			Log.e("mark", "去请求的一级:brand_id:" + treeElement.getBrandId());
			params.put("brand_id", treeElement.getBrandId());
		} else {
			Log.e("mark", "brand_id is 0 ");
			params.put("brand_id", "0");
		}

		params.put("points", mApp.getPoints());
		request.requestStoreGetStoresWithDoneHandler("", params,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						StoreBaseBean baseBean = ProjectDataManage
								.getInstance().getStoreBaseBean();
						if (null != baseBean) {
							if (baseBean.getData() != null) {
								storeList = baseBean.getData();
								if (storeList != null && storeList.size() > 0) {
									adapter.setList(storeList);
//									currentStore = storeList.get(0);
								}
							}

						}

					}
				});
	}

	private void bind() {
		request = new ProjectHttpRequestImpl(this, true);
		RequestParams params = new RequestParams();
		params.put("client_id", ProjectHttpRequestInterface.client_id_key);
		params.put("token", token);
		final String storeId = String.valueOf(currentStore.getStore_id());
		params.put("store_id", storeId);
		String carId = Preferences.getSharedPreferences(mApp, "carId", "");
		Log.e("mark", "bind() carId:"+carId);
		params.put("car_id", carId);
		request.requestBindStoreWithDoneHandler("", params,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						Log.e("mark", "bind content:"+content);
						BaseBean<?> bean = dataManager.getBaseBean();
						if(bean == null){
							Toast.makeText(BindStoreActivity.this, "bean is null!!!",
									Toast.LENGTH_LONG).show();
							return;
						}
						if (bean.getCode() == 200) {
							Toast.makeText(BindStoreActivity.this, "绑定4s店成功!",
									Toast.LENGTH_LONG).show();
							
							String carId = Preferences.getSharedPreferences(mApp, "carId", "");
							String default_car_id = Preferences.getSharedPreferences(mApp, "default_car_id", carId);
							Log.e("mark", "default_car_id:"+default_car_id);
							getCarInfo(default_car_id);
						}else{
							Toast.makeText(BindStoreActivity.this, bean.getMsg(),
									Toast.LENGTH_LONG).show();
						}
					}
				});
	}

	private void submit() {
		if (bundle != null) {
			String username = bundle.getString("username");
			String tel = bundle.getString("tel");
			String carNum = bundle.getString("carNum");
			String carFrameNum = bundle.getString("carFrameNum");
			String carEngineNum = bundle.getString("carEngineNum");
			int areaId = bundle.getInt("areaId");
			int cityId = bundle.getInt("cityId");
			int provinceId = bundle.getInt("provinceId");
			String buyCarTime = bundle.getString("buyCarTime");
			String checkEndTime = bundle.getString("checkEndTime");
			int sex = bundle.getInt("sex");
			String city_code_id = bundle.getString("city_code_id");
			// TODO 123
			String plate_area = bundle.getString("plate_area");
			String brand1_id = bundle.getString("brand1_id");
			String brand2_id = bundle.getString("brand2_id");
			String brand3_id = bundle.getString("brand3_id");
			String brand4_id = bundle.getString("brand4_id");

			String storeId = Preferences.getSharedPreferences(mApp, "storeId","");
			RequestParams params = new RequestParams();
			params.put("client_id", ProjectHttpRequestInterface.client_id_key);
			params.put("token", token);
			params.put("member_truename", username);// 姓名
			params.put("member_sex", String.valueOf(sex));// 性别(3=保密,2=女,1=男)
			params.put("member_provinceid", String.valueOf(provinceId));// 省份ID
			params.put("member_cityid", String.valueOf(cityId));// 城市ID
			params.put("member_areaid", String.valueOf(areaId));// 区域ID

			params.put("store_id", storeId);// 店铺ID
			params.put("brand1_id", brand1_id);// 品牌ID
			params.put("brand2_id", brand2_id);// 车系ID
			params.put("brand3_id", brand3_id);// 车型ID
			params.put("brand4_id", brand4_id);// 车款ID
			Log.e("mark", "plate_area:" + plate_area);
			Log.e("mark", "plate_number:" + carNum);
			params.put("plate_area", plate_area);// 车牌前缀(如:陕 -
			// APP端固定死全国车牌地区前缀选择框)
			params.put("plate_number", carNum);
			// 车牌号
			params.put("chassis_number", carFrameNum);// 车架号
			params.put("engine_number", carEngineNum);// 发动机号
			params.put("buy_date", buyCarTime);// 购车日期
			params.put("regist_number", "");// 登记证书编号
			params.put("insurance_id", "");// 保险公司选择ID(请传保险公司ID)
			params.put("applicant_date", "");// 投保日期
			params.put("city_code_id", city_code_id);
			Log.e("mark", "str:" + params.toString());
			request = new ProjectHttpRequestImpl(this, true);
			request.requestRegUser2WithDoneHandler("", params,
					new AsyncHttpResponseHandler() {
						@Override
						public void onSuccess(String content) {
							BaseBean<Map> bean = (BaseBean<Map>) dataManager
									.getBaseBean();
							if (bean != null) {
								if (bean.getCode() == 200) {
									Map map = bean.getData();
									if (map != null) {
										String car_id = map.get("car_id")
												.toString();
										// Log.e("mark",
										// "car_id:"
										// + map.get("car_id")
										// .toString());
										Preferences.setEditor(mApp, "carId", car_id);
										Preferences.setEditor(mApp, "default_car_id", car_id);
										getCarInfo(car_id);
									}
								}else{
									Toast.makeText(
											BindStoreActivity.this,
											bean.getMsg(),
											Toast.LENGTH_SHORT).show();
								}
							}else{
								Toast.makeText(
										BindStoreActivity.this,
										"submit() bean is null!!!",
										Toast.LENGTH_SHORT).show();
							}
						}
					});
		}
	}

	private void getCarInfo(String carId) {
		request = new ProjectHttpRequestImpl(this, true);
		RequestParams params = new RequestParams();
		params.put("car_id", carId);
		params.put("client_id", ProjectHttpRequestInterface.client_id_key);
		params.put("token",
				Preferences.getSharedPreferences(this, "user_token", ""));
		request.requestUserCarGetWithDoneHandler("", params,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						CarInfoBaseBean baseBean = dataManager
								.getCarInfoBaseBean();
						if (baseBean != null) {
							if (baseBean.getCode() == 200) {
								CarInfo info = baseBean.getData();
								Preferences.setEditor(mApp, "default_car_num", info.getNative_plate());
								// TreeElement element = new TreeElement();
								// element.setBrandId(info.getBrand1_id());
								// element.setBrandId1(info.getBrand2_id());
								// element.setBrandId2(info.getBrand3_id());
								// element.setBrandId3(info.getBrand4_id());
								// element.setTitle(info.getCar_name());
								// dataManager.setElement(element);
								dataManager.setDefaultCarInfo(info);
								Intent intent = new Intent(
										BindStoreActivity.this,
										MainActivity.class);
								startActivity(intent);
								mActManager.popAllByKey(REGISTER_KEY);
							} else {
								Toast.makeText(
										BindStoreActivity.this,
										 baseBean.getMsg(),
										Toast.LENGTH_SHORT).show();
							}
						}else{
							Toast.makeText(
									BindStoreActivity.this,
									 "getCarInfo CarInfoBaseBean is null!!!",
									Toast.LENGTH_SHORT).show();
						}
					}
				});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			back();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_bind:
			if (rb01.isChecked() && currentStore != null) {
				if(type_action == 0){//register2 
					submit();//提交数据完成以后，调用getCarInfo，然后到主页
				}else if(type_action == 1){//login
					bind();//bind 完成调用getcarinfo，然后到主页
				}
			} else {
				Toast.makeText(this, "请选择服务点!", Toast.LENGTH_SHORT).show();
			}
			break;
		}
	}
}
